package kp.rpc.server.wrapper;

import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.parsetools.RecordParser;
import kp.rpc.protocol.ProtocolConstant;

/**
 * 装饰者模式,使用recordParser对原有的buffer处理能力进行增强
 */
public class TcpBufferHandlerWrapper implements Handler<Buffer> {
    private final RecordParser parser;

    public TcpBufferHandlerWrapper(Handler<Buffer> bufferHandler) {
        this.parser = initRecordParse(bufferHandler);
    }

    private RecordParser initRecordParse(Handler<Buffer> bufferHandler) {
        //构造parser
        RecordParser recordParser = RecordParser.newFixed(ProtocolConstant.MESSAGE_HEADER_LENGTH);
        recordParser.setOutput(new Handler<Buffer>() {
            //初始化
            int size = -1;
            Buffer resultBuffer = Buffer.buffer();

            @Override
            public void handle(Buffer buffer) {
                if (size == -1) {
                    //先读取消息体长度,赋值给size
                    size = buffer.getInt(13);
                    //设置后续读取内容的长度-bodySize
                    recordParser.fixedSizeMode(size);
                    //写入头消息到结果
                    resultBuffer.appendBuffer(buffer);
                } else {
                    //写入体信息到结果
                    resultBuffer.appendBuffer(buffer);
                    //已拼接为完整的buffer
                    bufferHandler.handle(resultBuffer);
                    //重置一轮
                    recordParser.fixedSizeMode(ProtocolConstant.MESSAGE_HEADER_LENGTH);
                    size = -1;
                    resultBuffer = Buffer.buffer();
                }
            }
        });
        return recordParser;
    }

    @Override
    public void handle(Buffer event) {
        parser.handle(event);
    }
}
